package com.bac.bacplatform;

import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.bac.http.VolleyErrorHelper.CommenErrorHandler;
import com.bac.javabeans.Principal;
import com.bac.utils.Config;
import com.bac.utils.Storage;
import com.bac.utils.Util;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class LoginActivity extends BaseActivity implements OnClickListener,
		CommenErrorHandler {

	private String mPhoneString;// = "15895874219" ;//= "Scott";
	private String mPasswordString;// = "123456";// = "123456";

	private EditText mEditTextPhone, mEditTextPassword;
	private ImageButton mClearPhone, mClearPassword;

	private TextView forgetpwdTextView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		findViewById(R.id.title_left).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
	}

	@Override
	public void init() {

		forgetpwdTextView = (TextView) findViewById(R.id.login_forget);
		forgetpwdTextView.setOnClickListener(this);

		TextView registbt = (TextView) findViewById(R.id.bt_register);
		registbt.setOnClickListener(this);

		Button okButton = (Button) findViewById(R.id.login_ok_btn);
		okButton.setOnClickListener(this);

		mEditTextPhone = (EditText) findViewById(R.id.login_phoneNumber);

		mEditTextPassword = (EditText) findViewById(R.id.login_password);

		mClearPhone = (ImageButton) findViewById(R.id.btn_clear_phone);

		mClearPassword = (ImageButton) findViewById(R.id.btn_clear_password);

		mClearPhone.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mEditTextPhone.setText("");
			}
		});

		mClearPassword.setOnClickListener(new OnClickListener() {
			@Override 
			public void onClick(View v) {
				mEditTextPassword.setText("");
			}
		});
		mEditTextPhone.addTextChangedListener(textWatcher);
		mEditTextPhone.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					if (mEditTextPhone.getText().toString() != null
							&& !("").equals(mEditTextPhone.getText().toString())) {
						mClearPhone.setVisibility(View.VISIBLE);
						mClearPassword.setVisibility(View.INVISIBLE);
					}
				} else {
					mClearPhone.setVisibility(View.INVISIBLE);
				}
			}
		});
		mEditTextPassword.addTextChangedListener(textWatcher);
	}

	TextWatcher textWatcher = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void afterTextChanged(Editable s) {
			if (mEditTextPhone.hasFocus()
					&& mEditTextPhone.getText().toString() != null
					&& !("").equals(mEditTextPhone.getText().toString())) {
				mClearPhone.setVisibility(View.VISIBLE);
			} else {
				mClearPhone.setVisibility(View.INVISIBLE);
			}

			if (mEditTextPassword.hasFocus()
					&& mEditTextPassword.getText().toString() != null
					&& !("").equals(mEditTextPassword.getText().toString())) {
				mClearPassword.setVisibility(View.VISIBLE);
			} else {
				mClearPassword.setVisibility(View.INVISIBLE);
			}

		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_ok_btn:
			login();
			break;
		case R.id.bt_register:
			Intent intentToRegist = new Intent(LoginActivity.this,
					RegistActivity.class);
			startActivityIn(intentToRegist);
			// getCurrentuser();
			break;
		case R.id.login_forget:
			Intent intentToLoginPwd = new Intent(LoginActivity.this,
					LoginPwdActivity.class);
			startActivity(intentToLoginPwd);
			break;
		default:
			break;
		}
	}

	public void login() {
		/**
		 * 成功返回结果
		 */
		Listener<String> sL = new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {

				dismissLoadingProgressNow();
				Log.i(getClass().getName()+"----", response.toString());

				HashMap<String, String> result = new Gson().fromJson(
						new String(response),
						new TypeToken<HashMap<String, String>>() {
						}.getType());
				if (result != null && result.containsKey("code")) {
					hanlderErrorShowMessage(result.get("msg"));
				}else{
					Gson gson = new Gson();
					Principal principal = gson.fromJson(response, Principal.class);
					
					// 本地保存账号密码，是否要保存手势密码后续待定
					Storage.saveString(getApplicationContext(),
							Config.USER_ACCOUNT_KEY, mPhoneString);
					Storage.saveString(getApplicationContext(),
							Config.USER_PWD_KEY, mPasswordString);

					// 设置全局个人信息
					Config.UserGeneralInfo.setUserInfo(principal);

					Intent intentToMain = new Intent(LoginActivity.this,
							MainActivity.class);
					intentToMain.putExtra("islogin", true);
					intentToMain.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivityIn(intentToMain);
					finish();
				}
			}
		};

		mPhoneString = mEditTextPhone.getText().toString().trim();
		mPasswordString = mEditTextPassword.getText().toString().trim();
		if (mPhoneString.length() <= 0) {
			showToast(R.string.phone_none);
			return;
		} else if (mPasswordString.length() <= 0) {
			showToast(R.string.password_none);
			return;
		}

		showLoadingProgress();
		String path = Config.URL_LOGIN;
		Map<String, String> map = new HashMap<String, String>();
		map.put("username", mPhoneString);
		map.put("password", mPasswordString);
		map.put("gesture", "false");
		Log.i(getClass().getName(), "username: " + mPhoneString + " password: "
				+ mPasswordString);
		Util.httpStringPost(path, sL, this, map);
	}

	public void getCurrentuser() {
		/**
		 * 成功返回结果
		 */
		Listener<String> sL = new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				dismissLoadingProgress();
				Log.i("TAG----success", response.toString());
			}
		};

		String path = Config.URL_CURRENT_USER;
		Util.httpRequestToGet(path, sL, this);
	}

	@Override
	public void hanlderTimeoutError() {
		super.hanlderTimeoutError();
	}

	@Override
	public void hanlderErrorShowMessage(String message) {
		super.hanlderErrorShowMessage(message);
	}

	@Override
	public void hanlderAutorError() {
		super.hanlderAutorError();
	}

	@Override
	public void hanlderUnknowError() {
		super.hanlderUnknowError();
		showAlertDialog("提示", "用户名或密码错误");
	}

	@Override
	public void hanlderNetworkError() {
		super.hanlderNetworkError();
	}

//	private long firstTime = 0;

//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		// TODO Auto-generated method stub
//		if(keyCode == KeyEvent.KEYCODE_BACK){
//				
//			long secondTime = System.currentTimeMillis();
//			if (secondTime - firstTime > 1500) {// 
//				Toast.makeText(LoginActivity.this, "再按一次退出程序",
//						Toast.LENGTH_SHORT).show();
//				firstTime = secondTime;// 
//				return true;
//			} else {
//				BacApplication.getInstance().exit(); 
////				finish();
//			}
//			return true;
//			
//		}
//		return super.onKeyDown(keyCode, event);
//	}
	
}
